package repo

import (
	gorm "github.com/jinzhu/gorm"

	"github.com/pingcap-incubator/tidb-dashboard/pkg/model"
)

// ListAllInstance 查询所有的实例
func ListAllInstance(db *gorm.DB) ([]model.TidbInstance, error) {
	var instances []model.TidbInstance
	err := db.Raw("SELECT * FROM tidb_dashboard.tidb_instance ORDER BY `index` asc").
		Scan(&instances).Error
	if err != nil {
		return nil, ErrExecute.Wrap(err, "list all instance err")
	}
	return instances, nil
}

// AddInstance 添加实例
func AddInstance(db *gorm.DB, instance *model.TidbInstance) error {
	if err :=
		db.Table(InstanceTable).
			Create(&instance).
			Error; err != nil {
		return ErrExecute.Wrap(err, "insert instance error")
	}
	return nil
}

// UpdateInstance  修改实例
func UpdateInstance(db *gorm.DB, instance *model.TidbInstance, ID uint) error {
	if err :=
		db.Table(InstanceTable).
			Model(model.TidbInstance{}).
			Where("id= ?", ID).
			Update(&instance).
			Error; err != nil {
		return ErrExecute.Wrap(err, "update instance error")
	}
	return nil
}

// DeleteInstance 删除实例
func DeleteInstance(db *gorm.DB, ID uint) error {
	if err :=
		db.Table(InstanceTable).
			Where("id = ?", ID).
			Delete(model.TidbInstance{}).Error; err != nil {
		return ErrExecute.Wrap(err, "delete instance error")
	}
	return nil
}

// GetInstance 获取实例
func GetInstance(db *gorm.DB, instanceID uint) (*model.TidbInstance, error) {
	var instances []model.TidbInstance
	err := db.Table(InstanceTable).Where("id = ? ", instanceID).Scan(&instances).Error
	if err != nil {
		return nil, ErrExecute.Wrap(err, "get instance error")
	}
	if len(instances) == 0 {
		return nil, nil
	}
	return &instances[0], nil
}

// UpdateInstanceStatus  修改实例是否启用状态
func UpdateInstanceStatus(db *gorm.DB, ID uint, status uint8) error {
	if err :=
		db.Table(InstanceTable).
			Model(model.TidbInstance{}).
			Where("id= ?", ID).
			Update("status", status).
			Error; err != nil {
		return ErrExecute.Wrap(err, "update instance status error")
	}
	return nil
}
